<template>
  <div class="task-form">
    <el-form
        ref="taskFormRef"
        :model="localFormData"
        :rules="taskRules"
        label-width="120px">

      <el-form-item label="任务名称" prop="name">
        <el-input
            v-model="localFormData.name"
            placeholder="请输入任务名称"
            clearable>
        </el-input>
      </el-form-item>

      <!-- 航线配置 -->
      <el-card class="config-section" shadow="never">
        <template #header>
          <span>航线配置</span>
        </template>

        <el-form-item label="出发城市" prop="departure">
          <el-select v-model="localFormData.departure" placeholder="选择出发城市" filterable>
            <el-option
                v-for="airport in airports"
                :key="airport.value"
                :label="airport.label"
                :value="airport.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目的地" prop="destination">
          <el-select v-model="localFormData.destination" placeholder="选择目的地" filterable>
            <el-option
                v-for="airport in airports"
                :key="airport.value"
                :label="airport.label"
                :value="airport.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="行程类型" prop="tripType">
          <el-radio-group v-model="localFormData.tripType">
            <el-radio label="oneway">单程</el-radio>
            <el-radio label="roundtrip">往返</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="乘客信息">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-input-number v-model="localFormData.adults" :min="1" :max="9"></el-input-number>
              <span class="passenger-label">成人</span>
            </el-col>
            <el-col :span="8">
              <el-input-number v-model="localFormData.children" :min="0" :max="8"></el-input-number>
              <span class="passenger-label">儿童</span>
            </el-col>
            <el-col :span="8">
              <el-input-number v-model="localFormData.infants" :min="0" :max="8"></el-input-number>
              <span class="passenger-label">婴儿</span>
            </el-col>
          </el-row>
        </el-form-item>
      </el-card>

      <!-- 动态日期配置 -->
      <el-card class="config-section" shadow="never">
        <template #header>
          <span>动态爬取配置</span>
        </template>

        <el-form-item label="基准日期" prop="baseDate">
          <el-date-picker
              v-model="localFormData.baseDate"
              type="date"
              placeholder="选择开始日期"
              :disabled-date="disabledDate"
              value-format="YYYY-MM-DD">
          </el-date-picker>
          <div class="form-tip">系统将以此日期为基准计算搜索日期</div>
        </el-form-item>

        <el-form-item label="爬取周期" prop="crawlCycle">
          <el-input-number v-model="localFormData.crawlCycle" :min="1" :max="30"></el-input-number>
          <span class="unit">天</span>
          <div class="form-tip">每次搜索的时间间隔</div>
        </el-form-item>

        <el-form-item label="执行次数" prop="executionCount">
          <el-input-number v-model="localFormData.executionCount" :min="1" :max="10"></el-input-number>
          <span class="unit">次</span>
          <div class="form-tip">每次定时任务执行时搜索的次数</div>
        </el-form-item>

        <!-- 预览效果 -->
        <el-form-item label="预览效果">
          <el-card class="preview-card" shadow="never">
            <div class="preview-title">下次执行时将搜索以下时间段：</div>
            <div v-for="(preview, index) in datePreview" :key="index" class="preview-item">
              <el-tag :type="index === 0 ? 'primary' : 'info'" size="small">
                第{{ index + 1 }}次
              </el-tag>
              <span class="preview-dates">{{ preview }}</span>
            </div>
          </el-card>
        </el-form-item>
      </el-card>

      <!-- 调度配置 -->
      <el-card class="config-section" shadow="never">
        <template #header>
          <span>调度配置</span>
        </template>

        <el-form-item label="执行计划" prop="cronExpression">
          <el-input v-model="localFormData.cronExpression" placeholder="如: 0 0 8 * * ? (每天8点)">
            <template #append>
              <el-button @click="showCronHelper = true" :icon="QuestionFilled">选择</el-button>
            </template>
          </el-input>
          <div class="cron-description">
            {{ getCronDescription(localFormData.cronExpression) }}
          </div>
        </el-form-item>

        <el-form-item label="导出路径" prop="exportPath">
          <el-input v-model="localFormData.exportPath" placeholder="./exports">
            <template #prepend>路径</template>
          </el-input>
        </el-form-item>

        <el-form-item label="导出选项">
          <el-checkbox v-model="localFormData.exportLowestPriceOnly">仅导出最低价格</el-checkbox>
        </el-form-item>
      </el-card>

      <!-- 邮件通知配置 -->
      <el-card class="config-section" shadow="never">
        <template #header>
          <span>邮件通知</span>
        </template>

        <el-form-item label="启用通知">
          <el-switch v-model="localFormData.emailNotification"></el-switch>
        </el-form-item>

        <el-form-item v-if="localFormData.emailNotification" label="接收邮箱" prop="emailRecipients">
          <el-select
              v-model="localFormData.emailRecipients"
              multiple
              filterable
              allow-create
              placeholder="输入邮箱地址，支持多个"
              style="width: 100%">
            <el-option
                v-for="email in commonEmails"
                :key="email"
                :label="email"
                :value="email">
            </el-option>
          </el-select>
          <div class="form-tip">任务执行完成后将发送包含Excel文件的邮件通知</div>
        </el-form-item>
      </el-card>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="submitting" :icon="isEditing ? Edit : Plus">
          {{ isEditing ? '更新任务' : '创建任务' }}
        </el-button>
        <el-button @click="handleReset" :icon="RefreshLeft" v-if="!isEditing">重置</el-button>
        <el-button @click="handleCancel" plain>取消</el-button>
      </el-form-item>
    </el-form>

    <!-- Cron表达式帮助对话框 -->
    <el-dialog v-model="showCronHelper" title="Cron表达式选择" width="70%">
      <CronHelper @select="onCronSelect" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import {
  Plus,
  Edit,
  RefreshLeft,
  QuestionFilled
} from '@element-plus/icons-vue'
import CronHelper from '@/components/CronHelper.vue'
import { parseCronExpression } from '@/utils/helpers'
import airports from "@/utils/airports.js";

// Props
const props = defineProps({
  formData: {
    type: Object,
    required: true
  },
  isEditing: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['submit', 'cancel', 'reset'])

// 响应式数据
const taskFormRef = ref()
const submitting = ref(false)
const showCronHelper = ref(false)
const localFormData = reactive({ ...props.formData })

// 监听外部数据变化
watch(() => props.formData, (newData) => {
  Object.assign(localFormData, newData)
}, { deep: true })

const commonEmails = ['1905333495@qq.com']

// 验证规则
const taskRules = {
  name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' },
    { min: 2, max: 50, message: '任务名称长度在2-50个字符', trigger: 'blur' }
  ],
  departure: [
    { required: true, message: '请选择出发城市', trigger: 'change' }
  ],
  destination: [
    { required: true, message: '请选择目的地', trigger: 'change' }
  ],
  baseDate: [
    { required: true, message: '请选择基准日期', trigger: 'change' }
  ],
  crawlCycle: [
    { required: true, message: '请设置爬取周期', trigger: 'change' }
  ],
  executionCount: [
    { required: true, message: '请设置执行次数', trigger: 'change' }
  ],
  cronExpression: [
    { required: true, message: '请输入Cron表达式', trigger: 'blur' }
  ],
  exportPath: [
    { required: true, message: '请输入导出路径', trigger: 'blur' }
  ],
  emailRecipients: [
    { validator: validateEmails, trigger: 'change' }
  ]
}

// 计算属性
const datePreview = computed(() => {
  if (!localFormData.baseDate || !localFormData.crawlCycle || !localFormData.executionCount) {
    return []
  }

  const baseDate = new Date();
  const previews = []

  for (let i = 0; i < localFormData.executionCount; i++) {
    const departDate = new Date(baseDate)
    departDate.setDate(departDate.getDate() + (i * localFormData.crawlCycle))

    let preview = departDate.toISOString().split('T')[0]

    if (localFormData.tripType === 'roundtrip') {
      const returnDate = new Date(departDate)
      returnDate.setDate(returnDate.getDate() + localFormData.roundTripDays)
      preview += ' - ' + returnDate.toISOString().split('T')[0]
    }

    previews.push(preview)
  }

  return previews
})

// 方法
function disabledDate(time) {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

function validateEmails(rule, value, callback) {
  if (!localFormData.emailNotification) {
    callback()
    return
  }

  if (!value || value.length === 0) {
    callback(new Error('启用邮件通知时必须填写接收邮箱'))
    return
  }

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  const invalidEmails = value.filter(email => !emailRegex.test(email))

  if (invalidEmails.length > 0) {
    callback(new Error(`邮箱格式不正确: ${invalidEmails.join(', ')}`))
    return
  }

  callback()
}

async function handleSubmit() {
  if (!taskFormRef.value) return

  try {
    await taskFormRef.value.validate()
    submitting.value = true
    emit('submit', { ...localFormData })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

function handleReset() {
  emit('reset')
}

function handleCancel() {
  emit('cancel')
}

function onCronSelect(cronExpression) {
  localFormData.cronExpression = cronExpression
  showCronHelper.value = false
}

function getCronDescription(cron) {
  return parseCronExpression(cron)
}
</script>

<style scoped>
.config-section {
  margin-bottom: 20px;
  background: #fafafa;
}

.config-section :deep(.el-card__header) {
  background: #f0f2f5;
  font-weight: bold;
}

.preview-card {
  background: #f8f9fa;
  border: 1px dashed #d0d7de;
}

.preview-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #24292f;
}

.preview-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.preview-item:last-child {
  margin-bottom: 0;
}

.preview-dates {
  margin-left: 10px;
  font-family: monospace;
  color: #0969da;
}

.unit {
  margin-left: 8px;
  color: #656d76;
}

.passenger-label {
  margin-left: 5px;
  font-size: 12px;
  color: #656d76;
}

.cron-description {
  font-size: 12px;
  color: #656d76;
  margin-top: 5px;
}

.form-tip {
  font-size: 12px;
  color: #656d76;
  margin-top: 5px;
}
</style>